package com.study.manage.mvc.common;

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

    public Map<String, String> uploadFile(String key, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String, String> map = new HashMap<String, String>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            UploadManager uploadManager = new UploadManager();
            uploadManager.put(mf.getBytes(), key, getUpToken(key));
            map.put("name", key);
            map.put("path", qiniuUrl + key);
        }
        return map;
    }



    public List<Map<String, String>> uploadFiles(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        String userDir = "0";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        UploadManager uploadManager = new UploadManager();
        int i = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile imgFile = entity.getValue();
            String tfsName = imgFile.getOriginalFilename();
            Map<String, String> map = new HashMap<String, String>();
            BufferedImage bi = ImageIO.read(imgFile.getInputStream());
            String fileName = new StringBuilder("pic_album_ad_").append(userDir).append("_")
                    .append(new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()))
                    .append(RandomUtils.nextLong(1000, 10000)).append("_").append(i).append("_wh")
                    .append(bi.getWidth()).append("x").append(bi.getHeight()).toString();
            String suffix = tfsName.indexOf(".") != -1
                    ? tfsName.substring(tfsName.lastIndexOf("."), tfsName.length()) : null;
            String key = fileName + suffix;
            uploadManager.put(imgFile.getBytes(), key, getUpToken());

            map.put("name", fileName);
            map.put("path", qiniuUrl + key);
            list.add(map);
            i++;
            return list;
        }
        return list;
    }

    /**
     * 文本编辑器
     * 
     */
    @ResponseBody
    @RequestMapping(path = "uploadConf", method = RequestMethod.POST)
    public void uploadConf(String action, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (!StringUtils.isEmpty(action) && "/uploadFiles".equals(action)) {

            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String userDir = "0";
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            UploadManager uploadManager = new UploadManager();
            Map<String, String> map = new HashMap<String, String>();
            int i = 0;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile imgFile = entity.getValue();
                String tfsName = imgFile.getOriginalFilename();
                BufferedImage bi = ImageIO.read(imgFile.getInputStream());
                String fileName = new StringBuilder("pic_album_ad_").append(userDir).append("_")
                        .append(new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()))
                        .append(RandomUtils.nextLong(1000, 10000)).append("_").append(i)
                        .append("_wh").append(bi.getWidth()).append("x").append(bi.getHeight())
                        .toString();

                String suffix = tfsName.indexOf(".") != -1
                        ? tfsName.substring(tfsName.lastIndexOf("."), tfsName.length()) : null;
                String key = fileName + suffix;
                uploadManager.put(imgFile.getBytes(), key, getUpToken());

                map.put("name", fileName);
                map.put("url", qiniuUrl + "/" + key);
                map.put("originalName", fileName);
                map.put("original", fileName);
                map.put("size", "");
                map.put("type", suffix);
                map.put("state", "SUCCESS");
                list.add(map);
                i++;
            }
            response.getWriter().print(jsonMapper.toJson(map));
        } else if (!StringUtils.isEmpty(action) && "/uploadVideo".equals(action)) {

            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String userDir = "0";
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            UploadManager uploadManager = new UploadManager();
            Map<String, String> map = new HashMap<String, String>();
            int i = 0;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile imgFile = entity.getValue();
                String tfsName = imgFile.getOriginalFilename();
                String fileName = new StringBuilder("pic_album_ad_").append(userDir).append("_")
                        .append(new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()))
                        .toString();
                String suffix = tfsName.indexOf(".") != -1
                        ? tfsName.substring(tfsName.lastIndexOf("."), tfsName.length()) : null;
                String key = fileName + suffix;
                uploadManager.put(imgFile.getBytes(), key, getUpToken());

                map.put("name", fileName);
                map.put("url", qiniuUrl + "/" + key);
                map.put("originalName", fileName);
                map.put("original", fileName);
                map.put("size", "");
                map.put("type", suffix);
                map.put("state", "SUCCESS");
                list.add(map);
                i++;
            }
            response.getWriter().print(jsonMapper.toJson(map));
        }
    }

    @ResponseBody
    @RequestMapping(path = "uploadConf", method = RequestMethod.GET)
    public void uploadConf(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

    }

    /**
     * 单图片上传
     */
    @RequestMapping(path = "token", method = RequestMethod.GET)
    public void token(HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("uptoken", this.getUpToken());
        map.put("qiniuUrl", this.qiniuUrl);
        map.put("bucket", this.zone);
        response.getWriter().write(jsonMapper.toJson(map));
    }


    @ResponseBody
    @RequestMapping(path = "fetch", method = RequestMethod.GET)
    public Map<String, Object> fetch(String url, String key, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<>();
        try {
            BucketManager bucketManager = new BucketManager(Auth.create(ak, sk));
            bucketManager.fetch(url, zone, key);
            map.put("newUrl", this.qiniuUrl + key);
        } catch (Exception e) {
            // LOGGER.error("upload image error", e);
        }
        return map;
    }

}
